<template>
    <div class="score-summary-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search"/>
        <div class="page-content">
            <div class="head">
                <h3>科室汇总列表<span>(不包含子级科室)</span></h3>
                <btn-group :showBtn="showBtn" :code="{exportCode: 100003000004}" @toExport="toExport"/>
            </div>
            <el-table
                ref="tableData"
                :data="tableData"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                @sort-change="sortChange"
                class="data-table">
                <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="departmentName"
                    label="出院科室"
                    min-width="160"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    label="总病案例数"
                    prop="total"
                    sortable="custom"
                    align="center"
                    min-width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.total > 0" class="to-child-page" @click="toMRList(scope.row, 0)">{{scope.row.total}}</span>
                        <span v-else>{{scope.row.total}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="总缺陷"
                    min-width="90"
                    align="center"
                    show-overflow-tooltip>
                    <el-table-column
                        prop="defect"
                        label="例数"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.defect > 0" class="to-child-page" @click="toMRList(scope.row, 4)">{{scope.row.defect}}</span>
                            <span v-else>{{scope.row.defect}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="defectRate"
                        label="率"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{Math.abs(getZeroTwoNum(scope.row.defectRate * 100))}}%</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="defectRateCom"
                        label="率增减"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.defectRateCom !== null" :class="{'tooltips-red': scope.row.defectRateCom > 0, 'tooltips-blue': scope.row.defectRateCom < 0}">
                                <i v-if="scope.row.defectRateCom > 0" class="el-icon-top top"></i>
                                <i v-if="scope.row.defectRateCom < 0" class="el-icon-bottom bottom"></i>
                                {{Math.abs(getZeroTwoNum(scope.row.defectRateCom * 100))}}%
                            </span>
                            <span v-if="scope.row.defectRateCom === null">-</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    label="非编码缺陷"
                    min-width="90"
                    align="center"
                    show-overflow-tooltip>
                    <el-table-column
                        prop="noneCodingDefect"
                        label="例数"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.noneCodingDefect > 0" class="to-child-page" @click="toMRList(scope.row, 6)">{{scope.row.noneCodingDefect}}</span>
                            <span v-else>{{scope.row.noneCodingDefect}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="noneCodingDefectRate"
                        label="率"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{Math.abs(getZeroTwoNum(scope.row.noneCodingDefectRate * 100))}}%</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="noneCodingDefectRateCom"
                        label="率增减"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.noneCodingDefectRateCom !== null" :class="{'tooltips-red': scope.row.noneCodingDefectRateCom > 0, 'tooltips-blue': scope.row.noneCodingDefectRateCom < 0}">
                                <i v-if="scope.row.noneCodingDefectRateCom > 0" class="el-icon-top top"></i>
                                <i v-if="scope.row.noneCodingDefectRateCom < 0" class="el-icon-bottom bottom"></i>
                                {{Math.abs(getZeroTwoNum(scope.row.noneCodingDefectRateCom * 100))}}%
                            </span>
                            <span v-if="scope.row.noneCodingDefectRateCom === null">-</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    label="编码缺陷"
                    min-width="90"
                    align="center"
                    show-overflow-tooltip>
                    <el-table-column
                        prop="codingDefect"
                        label="例数"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.codingDefect > 0" class="to-child-page" @click="toMRList(scope.row, 5)">{{scope.row.codingDefect}}</span>
                            <span v-else>{{scope.row.codingDefect}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="codingDefectRate"
                        label="率"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span>{{Math.abs(getZeroTwoNum(scope.row.codingDefectRate * 100))}}%</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="codingDefectRateCom"
                        label="率增减"
                        min-width="90"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.codingDefectRateCom !== null" :class="{'tooltips-red': scope.row.codingDefectRateCom > 0, 'tooltips-blue': scope.row.codingDefectRateCom < 0}">
                                <i v-if="scope.row.codingDefectRateCom > 0" class="el-icon-top top"></i>
                                <i v-if="scope.row.codingDefectRateCom < 0" class="el-icon-bottom bottom"></i>
                                {{Math.abs(getZeroTwoNum(scope.row.codingDefectRateCom * 100))}}%
                            </span>
                            <span v-if="scope.row.codingDefectRateCom === null">-</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    label="国标平均得分"
                    min-width="90"
                    align="center"
                    show-overflow-tooltip>
                    <el-table-column
                        prop="nationAvgScore"
                        label="分值"
                        min-width="90"
                        align="center"
                        sortable="custom"
                        show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column
                        prop="nationAvgScoreCom"
                        label="增减"
                        min-width="90"
                        align="center"
                        sortable="custom"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.nationAvgScoreCom !== null" :class="{'tooltips-red': scope.row.nationAvgScoreCom > 0, 'tooltips-blue': scope.row.nationAvgScoreCom < 0}">
                                <i v-if="scope.row.nationAvgScoreCom > 0" class="el-icon-top top"></i>
                                <i v-if="scope.row.nationAvgScoreCom < 0" class="el-icon-bottom bottom"></i>
                                {{Math.abs(getZeroTwoNum(scope.row.nationAvgScoreCom))}}
                            </span>
                            <span v-if="scope.row.nationAvgScoreCom === null">-</span>
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    label="院标平均扣分"
                    align="center"
                    show-overflow-tooltip>
                    <el-table-column
                        prop="hospitalAvgDeduction"
                        label="分值"
                        min-width="110"
                        sortable="custom"
                        align="center"
                        show-overflow-tooltip>
                    </el-table-column>
                </el-table-column>
                <el-table-column
                    label="缺陷提示汇总"
                    min-width="90"
                    align="center"
                    show-overflow-tooltip>
                    <el-table-column
                        prop="noneCodingTipCount"
                        label="非编码"
                        min-width="90"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.noneCodingTipCount > 0" class="to-child-page" @click="toAnalysis(scope.row)">{{scope.row.noneCodingTipCount}}</span>
                            <span v-else>{{scope.row.noneCodingTipCount}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="codingTipCount"
                        label="编码"
                        min-width="90"
                        align="center"
                        show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.codingTipCount > 0" class="to-child-page" @click="toAnalysis(scope.row)">{{scope.row.codingTipCount}}</span>
                            <span v-else>{{scope.row.codingTipCount}}</span>
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="changePage"/>
        </div>
    </div>
</template>

<script>
    import {getSummaryDepList} from '@/api/summary-list/department'
    import {getSortString, getZeroTwoNum} from '@/utils/filters'
    import Pagination from '@/components/Pagination'
    import BtnGroup from '@/components/BtnGroup'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'index',
        data () {
            return {
                // 按钮显示
                showBtn: ['toExport'],
                // 表格数据
                tableData: [],
                // 排序字段
                sortMap: {},
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 100,
                // 排序方式
                sortType: '',
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 使用储存的数据，不去请求
                useStore: false,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 219 - 10 - 78 - 32
            this.tableHeight = height > 107 ? height : 107
            this.initPage()
        },
        mounted () {
            window.onresize = () => {
                // 其他元素高度60+50+48 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 219 - 10 - 78 - 32
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            getZeroTwoNum,
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (query) {
                    this.currentPage = query.pageIndex || 1
                    this.pageSize = query.pageSize || 20
                    this.sortType = query.orderBy
                }
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 获取机构名称
             * @param id 机构id
             */
            getCurrnetOrg (id) {
                let mechanismList = this.getLocalStorage('userInfo', 'mechanism')
                let res = mechanismList.filter(item => item.id === id)
                return res.length ? res[0].name : ''
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType,
                    start: data.start,
                    end: data.end,
                    orgId: data.orgId,
                    department: data.department,
                    departmentName: data.departmentName,
                    coder: data.coder,
                    isLast: data.isLast
                }
                if (!params.orderBy) params.orderBy = '`departmentName` desc'
                if (this.getSession(this.$route.name, 'getSummaryDepList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getSummaryDepList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                        this.total = res.data.total
                    }
                } else {
                    getSummaryDepList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getSummaryDepList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                            this.total = res.data.total
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
                this.setGetStore(this.$route.name, params)
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.submitSearch()
            },
            /**
             * 导出科室汇总列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (!params.orderBy) params.orderBy = '`departmentName` desc'
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                getSummaryDepList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data.rows)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('科室汇总列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    key: 'index', width: 10
                }, {
                    key: 'departmentName', width: 24
                }, {
                    key: 'total', width: 12
                }, {
                    key: 'defect', width: 12
                }, {
                    key: 'defectRate', width: 12
                }, {
                    key: 'defectRateCom', width: 12
                }, {
                    key: 'noneCodingDefect', width: 12
                }, {
                    key: 'noneCodingDefectRate', width: 12
                }, {
                    key: 'noneCodingDefectRateCom', width: 12
                }, {
                    key: 'codingDefect', width: 12
                }, {
                    key: 'codingDefectRate', width: 12
                }, {
                    key: 'codingDefectRateCom', width: 12
                }, {
                    key: 'nationAvgScore', width: 12
                }, {
                    key: 'nationAvgScoreCom', width: 12
                }, {
                    key: 'hospitalAvgDeduction', width: 20
                }, {
                    key: 'noneCodingTipCount', width: 12
                }, {
                    key: 'codingTipCount', width: 12
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                /* eslint-disable */
                worksheet.getRow(1).values = ['序号', '出院科室', '总病案例数', '总缺陷', , , '非编码缺陷', , , '编码缺陷', , , '国标平均得分', , '院标平均扣分', '缺陷提示汇总', ,]
                /* eslint-enable */
                worksheet.getRow(2).values = ['序号', '出院科室', '总病案例数', '例数', '率', '率增减', '例数', '率', '率增减', '例数', '率', '率增减', '分值', '增减', '院标平均扣分', '非编码', '编码']
                worksheet.columns = this.getHeader()
                worksheet.mergeCells('A1:A2')
                worksheet.mergeCells('B1:B2')
                worksheet.mergeCells('C1:C2')
                worksheet.mergeCells('O1:O2')
                worksheet.mergeCells('D1:F1')
                worksheet.mergeCells('G1:I1')
                worksheet.mergeCells('J1:L1')
                worksheet.mergeCells('M1:N1')
                worksheet.mergeCells('P1:Q1')
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].defectRate = Math.abs(getZeroTwoNum(data[i].defectRate * 100)) + '%'
                    data[i].defectRateCom = data[i].defectRateCom === null ? '-' : Math.abs(getZeroTwoNum(data[i].defectRateCom * 100)) + '%'
                    data[i].noneCodingDefectRate = Math.abs(getZeroTwoNum(data[i].noneCodingDefectRate * 100)) + '%'
                    data[i].noneCodingDefectRateCom = data[i].noneCodingDefectRateCom === null ? '-' : Math.abs(getZeroTwoNum(data[i].noneCodingDefectRateCom * 100)) + '%'
                    data[i].codingDefectRate = Math.abs(getZeroTwoNum(data[i].codingDefectRate * 100)) + '%'
                    data[i].codingDefectRateCom = data[i].codingDefectRateCom === null ? '-' : Math.abs(getZeroTwoNum(data[i].codingDefectRateCom * 100)) + '%'
                    data[i].nationAvgScoreCom = data[i].nationAvgScoreCom === null ? '-' : Math.abs(getZeroTwoNum(data[i].nationAvgScoreCom * 100)) + '%'
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getRow(data.length + 2).alignment = {vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('departmentName').alignment = {wrapText: true, vertical: 'middle', horizontal: 'left'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                })
            },
            /**
             * 前往缺陷类型分析
             * @param row 行数据
             */
            toAnalysis (row) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    ...query,
                    orgId: query.orgId,
                    department: row.departmentCode,
                    departmentName: row.departmentName,
                    resident: query.department ? row.resident : '',
                    pageIndex: 1
                }
                this.$store.dispatch('search/coverSearchFormItem', {
                    pageName: 'DepSummaryAnalysisIndex',
                    query: params
                })
                this.$router.push({name: 'DepSummaryAnalysisIndex'})
            },
            /**
             * 前往病案列表
             * @param row 行数据
             * @param val 参数值
             */
            toMRList (row, val) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    ...query,
                    department: row.departmentCode,
                    departmentName: row.departmentName,
                    defectSate: val,
                    pageIndex: 1,
                    orderBy: ''
                }
                this.$store.dispatch('search/coverSearchFormItem', {
                    pageName: 'DepSummaryMRList',
                    query: params
                })
                this.$router.push({name: 'DepSummaryMRList'})
            }
        },
        components: {
            BtnGroup,
            Pagination
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .score-summary-container {
        height: calc(100% - 10px);
        .page-content {
            height: calc(100% - 54px);
            background: #fff;
            padding: 0 10px;
        }
        .head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            h3 {
                font-size: 16px;
                color: #000;
                font-weight: 600;
                line-height: 48px;
                span {
                    font-size: 12px;
                    color: #7e7e7e;
                    font-weight: normal;
                    margin-left: 20px;
                }
            }
        }
    }
</style>
